3 * This is the MS SQL Server Native database abstraction layer.
5 * This program is free software; you can redistribute it and/or modify
6 * it under the terms of the GNU General Public License as published by
7 * the Free Software Foundation; either version 2 of the License, or
8 * (at your option) any later version.
10 * This program is distributed in the hope that it will be useful,
11 * but WITHOUT ANY WARRANTY; without even the implied warranty of
12 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 * GNU General Public License for more details.
15 * You should have received a copy of the GNU General Public License along
16 * with this program; if not, write to the Free Software Foundation, Inc.,
17 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
18 * http://www.gnu.org/copyleft/gpl.html
22 * @author Joel Penner <a-joelpe at microsoft dot com>
23 * @author Chris Pucci <a-cpucci at microsoft dot com>
24 * @author Ryan Biesemeyer <v-ryanbi at microsoft dot com>
25 * @author Ryan Schmidt <skizzerz at gmail dot com>
28 namespace Wikimedia\Rdbms
;
33 use Wikimedia\AtEase\AtEase
;
38 class DatabaseMssql
extends Database
{
40 protected $serverPort;
42 protected $useWindowsAuth = false;
44 protected $lastInsertId = null;
46 protected $lastAffectedRowCount = null;
48 protected $subqueryId = 0;
50 protected $scrollableCursor = true;
52 protected $prepareStatements = true;
53 /** @var stdClass[][]|null */
54 protected $binaryColumnCache = null;
55 /** @var stdClass[][]|null */
56 protected $bitColumnCache = null;
58 protected $ignoreDupKeyErrors = false;
60 protected $ignoreErrors = [];
62 public function implicitOrderby() {
66 public function unionSupportsOrderAndLimit() {
70 public function __construct( array $params ) {
71 $this->serverPort
= $params['port'];
72 $this->useWindowsAuth
= $params['UseWindowsAuth'];
74 parent
::__construct( $params );
77 protected function open( $server, $user, $password, $dbName, $schema, $tablePrefix ) {
78 if ( !function_exists( 'sqlsrv_connect' ) ) {
79 throw new DBConnectionError(
81 "Microsoft SQL Server Native (sqlsrv) functions missing.\n
82 You can download the driver from: http://go.microsoft.com/fwlink/?LinkId=123470"
88 if ( $schema !== null ) {
89 throw $this->newExceptionAfterConnectError( "Got schema '$schema'; not supported." );
92 $this->server
= $server;
94 $this->password
= $password;
97 if ( strlen( $dbName ) ) {
98 $connectionInfo['Database'] = $dbName;
100 if ( !$this->useWindowsAuth
) {
101 $connectionInfo['UID'] = $user;
102 $connectionInfo['PWD'] = $password;
105 AtEase
::suppressWarnings();
106 $this->conn
= sqlsrv_connect( $server, $connectionInfo ) ?
: null;
107 AtEase
::restoreWarnings();
109 if ( !$this->conn
) {
110 throw $this->newExceptionAfterConnectError( $this->lastError() );
114 $this->currentDomain
= new DatabaseDomain(
115 strlen( $dbName ) ?
$dbName : null,
119 } catch ( Exception
$e ) {
120 throw $this->newExceptionAfterConnectError( $e->getMessage() );
125 * Closes a database connection, if it is open
126 * Returns success, true if already closed
129 protected function closeConnection() {
130 return sqlsrv_close( $this->conn
);
134 * @param bool|MssqlResultWrapper|resource $result
135 * @return bool|MssqlResultWrapper
137 protected function resultObject( $result ) {
140 } elseif ( $result instanceof MssqlResultWrapper
) {
142 } elseif ( $result === true ) {
143 // Successful write query
146 return new MssqlResultWrapper( $this, $result );
152 * @return bool|MssqlResultWrapper|resource
154 protected function doQuery( $sql ) {
155 // several extensions seem to think that all databases support limits
156 // via LIMIT N after the WHERE clause, but MSSQL uses SELECT TOP N,
157 // so to catch any of those extensions we'll do a quick check for a
158 // LIMIT clause and pass $sql through $this->LimitToTopN() which parses
159 // the LIMIT clause and passes the result to $this->limitResult();
160 if ( preg_match( '/\bLIMIT\s*/i', $sql ) ) {
161 // massage LIMIT -> TopN
162 $sql = $this->LimitToTopN( $sql );
165 // MSSQL doesn't have EXTRACT(epoch FROM XXX)
166 if ( preg_match( '#\bEXTRACT\s*?\(\s*?EPOCH\s+FROM\b#i', $sql, $matches ) ) {
167 // This is same as UNIX_TIMESTAMP, we need to calc # of seconds from 1970
168 $sql = str_replace( $matches[0], "DATEDIFF(s,CONVERT(datetime,'1/1/1970'),", $sql );
173 // SQLSRV_CURSOR_STATIC is slower than SQLSRV_CURSOR_CLIENT_BUFFERED (one of the two is
174 // needed if we want to be able to seek around the result set), however CLIENT_BUFFERED
175 // has a bug in the sqlsrv driver where wchar_t types (such as nvarchar) that are empty
176 // strings make php throw a fatal error "Severe error translating Unicode"
177 if ( $this->scrollableCursor
) {
178 $scrollArr = [ 'Scrollable' => SQLSRV_CURSOR_STATIC
];
183 if ( $this->prepareStatements
) {
184 // we do prepare + execute so we can get its field metadata for later usage if desired
185 $stmt = sqlsrv_prepare( $this->conn
, $sql, [], $scrollArr );
186 $success = sqlsrv_execute( $stmt );
188 $stmt = sqlsrv_query( $this->conn
, $sql, [], $scrollArr );
189 $success = (bool)$stmt;
192 // Make a copy to ensure what we add below does not get reflected in future queries
193 $ignoreErrors = $this->ignoreErrors
;
195 if ( $this->ignoreDupKeyErrors
) {
196 // ignore duplicate key errors
197 // this emulates INSERT IGNORE in MySQL
198 $ignoreErrors[] = '2601'; // duplicate key error caused by unique index
199 $ignoreErrors[] = '2627'; // duplicate key error caused by primary key
200 $ignoreErrors[] = '3621'; // generic "the statement has been terminated" error
203 if ( $success === false ) {
204 $errors = sqlsrv_errors();
207 foreach ( $errors as $err ) {
208 if ( !in_array( $err['code'], $ignoreErrors ) ) {
214 if ( $success === false ) {
218 // remember number of rows affected
219 $this->lastAffectedRowCount
= sqlsrv_rows_affected( $stmt );
224 public function freeResult( $res ) {
225 sqlsrv_free_stmt( ResultWrapper
::unwrap( $res ) );
229 * @param IResultWrapper $res
232 public function fetchObject( $res ) {
233 // $res is expected to be an instance of MssqlResultWrapper here
234 return $res->fetchObject();
238 * @param IResultWrapper $res
241 public function fetchRow( $res ) {
242 return $res->fetchRow();
249 public function numRows( $res ) {
250 $res = ResultWrapper
::unwrap( $res );
252 $ret = sqlsrv_num_rows( $res );
253 if ( $ret === false ) {
254 // we cannot get an amount of rows from this cursor type
255 // has_rows returns bool true/false if the result has rows
256 $ret = (int)sqlsrv_has_rows( $res );
266 public function numFields( $res ) {
267 return sqlsrv_num_fields( ResultWrapper
::unwrap( $res ) );
275 public function fieldName( $res, $n ) {
276 return sqlsrv_field_metadata( ResultWrapper
::unwrap( $res ) )[$n]['Name'];
280 * This must be called after nextSequenceVal
283 public function insertId() {
284 return $this->lastInsertId
;
288 * @param MssqlResultWrapper $res
292 public function dataSeek( $res, $row ) {
293 return $res->seek( $row );
299 public function lastError() {
301 $retErrors = sqlsrv_errors( SQLSRV_ERR_ALL
);
302 if ( $retErrors != null ) {
303 foreach ( $retErrors as $arrError ) {
304 $strRet .= $this->formatError( $arrError ) . "\n";
307 $strRet = "No errors found";
317 private function formatError( $err ) {
318 return '[SQLSTATE ' .
319 $err['SQLSTATE'] . '][Error Code ' . $err['code'] . ']' . $err['message'];
325 public function lastErrno() {
326 $err = sqlsrv_errors( SQLSRV_ERR_ALL
);
327 if ( $err !== null && isset( $err[0] ) ) {
328 return $err[0]['code'];
334 protected function wasKnownStatementRollbackError() {
335 $errors = sqlsrv_errors( SQLSRV_ERR_ALL
);
339 // The transaction vs statement rollback behavior depends on XACT_ABORT, so make sure
340 // that the "statement has been terminated" error (3621) is specifically present.
341 // https://docs.microsoft.com/en-us/sql/t-sql/statements/set-xact-abort-transact-sql
342 $statementOnly = false;
343 $codeWhitelist = [ '2601', '2627', '547' ];
344 foreach ( $errors as $error ) {
345 if ( $error['code'] == '3621' ) {
346 $statementOnly = true;
347 } elseif ( !in_array( $error['code'], $codeWhitelist ) ) {
348 $statementOnly = false;
353 return $statementOnly;
356 public function serverIsReadOnly() {
357 $encDatabase = $this->addQuotes( $this->getDBname() );
359 "SELECT IS_READ_ONLY FROM SYS.DATABASES WHERE NAME = $encDatabase",
362 $row = $this->fetchObject( $res );
364 return $row ?
(bool)$row->IS_READ_ONLY
: false;
370 protected function fetchAffectedRowCount() {
371 return $this->lastAffectedRowCount
;
377 * @param mixed $table Array or string, table name(s) (prefix auto-added)
378 * @param mixed $vars Array or string, field name(s) to be retrieved
379 * @param mixed $conds Array or string, condition(s) for WHERE
380 * @param string $fname Calling function name (use __METHOD__) for logs/profiling
381 * @param array $options Associative array of options (e.g.
382 * [ 'GROUP BY' => 'page_title' ]), see Database::makeSelectOptions
383 * code for list of supported stuff
384 * @param array $join_conds Associative array of table join conditions
385 * (optional) (e.g. [ 'page' => [ 'LEFT JOIN','page_latest=rev_id' ] ]
386 * @return mixed Database result resource (feed to Database::fetchObject
387 * or whatever), or false on failure
388 * @throws DBQueryError
389 * @throws DBUnexpectedError
392 public function select( $table, $vars, $conds = '', $fname = __METHOD__
,
393 $options = [], $join_conds = []
395 $sql = $this->selectSQLText( $table, $vars, $conds, $fname, $options, $join_conds );
396 if ( isset( $options['EXPLAIN'] ) ) {
398 $this->scrollableCursor
= false;
399 $this->prepareStatements
= false;
400 $this->query( "SET SHOWPLAN_ALL ON" );
401 $ret = $this->query( $sql, $fname );
402 $this->query( "SET SHOWPLAN_ALL OFF" );
403 } catch ( DBQueryError
$dqe ) {
404 if ( isset( $options['FOR COUNT'] ) ) {
405 // likely don't have privs for SHOWPLAN, so run a select count instead
406 $this->query( "SET SHOWPLAN_ALL OFF" );
407 unset( $options['EXPLAIN'] );
408 $ret = $this->select(
410 'COUNT(*) AS EstimateRows',
417 // someone actually wanted the query plan instead of an est row count
418 // let them know of the error
419 $this->scrollableCursor
= true;
420 $this->prepareStatements
= true;
424 $this->scrollableCursor
= true;
425 $this->prepareStatements
= true;
428 return $this->query( $sql, $fname );
434 * @param mixed $table Array or string, table name(s) (prefix auto-added)
435 * @param mixed $vars Array or string, field name(s) to be retrieved
436 * @param mixed $conds Array or string, condition(s) for WHERE
437 * @param string $fname Calling function name (use __METHOD__) for logs/profiling
438 * @param array $options Associative array of options (e.g. [ 'GROUP BY' => 'page_title' ]),
439 * see Database::makeSelectOptions code for list of supported stuff
440 * @param array $join_conds Associative array of table join conditions (optional)
441 * (e.g. [ 'page' => [ 'LEFT JOIN','page_latest=rev_id' ] ]
442 * @return string The SQL text
444 public function selectSQLText( $table, $vars, $conds = '', $fname = __METHOD__
,
445 $options = [], $join_conds = []
447 if ( isset( $options['EXPLAIN'] ) ) {
448 unset( $options['EXPLAIN'] );
451 $sql = parent
::selectSQLText( $table, $vars, $conds, $fname, $options, $join_conds );
453 // try to rewrite aggregations of bit columns (currently MAX and MIN)
454 if ( strpos( $sql, 'MAX(' ) !== false ||
strpos( $sql, 'MIN(' ) !== false ) {
456 if ( is_array( $table ) ) {
459 $t = array_pop( $tables );
460 if ( is_array( $t ) ) {
461 $tables = array_merge( $tables, $t );
463 $bitColumns +
= $this->getBitColumns( $this->tableName( $t ) );
467 $bitColumns = $this->getBitColumns( $this->tableName( $table ) );
470 foreach ( $bitColumns as $col => $info ) {
472 "MAX({$col})" => "MAX(CAST({$col} AS tinyint))",
473 "MIN({$col})" => "MIN(CAST({$col} AS tinyint))",
475 $sql = str_replace( array_keys( $replace ), array_values( $replace ), $sql );
482 public function deleteJoin( $delTable, $joinTable, $delVar, $joinVar, $conds,
485 $this->scrollableCursor
= false;
487 parent
::deleteJoin( $delTable, $joinTable, $delVar, $joinVar, $conds, $fname );
488 } catch ( Exception
$e ) {
489 $this->scrollableCursor
= true;
492 $this->scrollableCursor
= true;
495 public function delete( $table, $conds, $fname = __METHOD__
) {
496 $this->scrollableCursor
= false;
498 parent
::delete( $table, $conds, $fname );
499 } catch ( Exception
$e ) {
500 $this->scrollableCursor
= true;
503 $this->scrollableCursor
= true;
509 * Estimate rows in dataset
510 * Returns estimated count, based on SHOWPLAN_ALL output
511 * This is not necessarily an accurate estimate, so use sparingly
512 * Returns -1 if count cannot be found
513 * Takes same arguments as Database::select()
514 * @param string $table
516 * @param string $conds
517 * @param string $fname
518 * @param array $options
519 * @param array $join_conds
522 public function estimateRowCount( $table, $var = '*', $conds = '',
523 $fname = __METHOD__
, $options = [], $join_conds = []
525 $conds = $this->normalizeConditions( $conds, $fname );
526 $column = $this->extractSingleFieldFromList( $var );
527 if ( is_string( $column ) && !in_array( $column, [ '*', '1' ] ) ) {
528 $conds[] = "$column IS NOT NULL";
531 // http://msdn2.microsoft.com/en-us/library/aa259203.aspx
532 $options['EXPLAIN'] = true;
533 $options['FOR COUNT'] = true;
534 $res = $this->select( $table, $var, $conds, $fname, $options, $join_conds );
538 $row = $this->fetchRow( $res );
540 if ( isset( $row['EstimateRows'] ) ) {
541 $rows = (int)$row['EstimateRows'];
549 * Returns information about an index
550 * If errors are explicitly ignored, returns NULL on failure
551 * @param string $table
552 * @param string $index
553 * @param string $fname
554 * @return array|bool|null
556 public function indexInfo( $table, $index, $fname = __METHOD__
) {
557 # This does not return the same info as MYSQL would, but that's OK
558 # because MediaWiki never uses the returned value except to check for
559 # the existence of indexes.
560 $sql = "sp_helpindex '" . $this->tableName( $table ) . "'";
561 $res = $this->query( $sql, $fname );
568 foreach ( $res as $row ) {
569 if ( $row->index_name
== $index ) {
570 $row->Non_unique
= !stristr( $row->index_description
, "unique" );
571 $cols = explode( ", ", $row->index_keys
);
572 foreach ( $cols as $col ) {
573 $row->Column_name
= trim( $col );
574 $result[] = clone $row;
576 } elseif ( $index == 'PRIMARY' && stristr( $row->index_description
, 'PRIMARY' ) ) {
577 $row->Non_unique
= 0;
578 $cols = explode( ", ", $row->index_keys
);
579 foreach ( $cols as $col ) {
580 $row->Column_name
= trim( $col );
581 $result[] = clone $row;
586 return $result ?
: false;
590 * INSERT wrapper, inserts an array into a table
592 * $arrToInsert may be a single associative array, or an array of these with numeric keys, for
595 * Usually aborts on failure
596 * If errors are explicitly ignored, returns success
597 * @param string $table
598 * @param array $arrToInsert
599 * @param string $fname
600 * @param array $options
604 public function insert( $table, $arrToInsert, $fname = __METHOD__
, $options = [] ) {
605 # No rows to insert, easy just return now
606 if ( !count( $arrToInsert ) ) {
610 if ( !is_array( $options ) ) {
611 $options = [ $options ];
614 $table = $this->tableName( $table );
616 if ( !( isset( $arrToInsert[0] ) && is_array( $arrToInsert[0] ) ) ) { // Not multi row
617 $arrToInsert = [ 0 => $arrToInsert ]; // make everything multi row compatible
620 // We know the table we're inserting into, get its identity column
622 // strip matching square brackets and the db/schema from table name
623 $tableRawArr = explode( '.', preg_replace( '#\[([^\]]*)\]#', '$1', $table ) );
624 $tableRaw = array_pop( $tableRawArr );
625 $res = $this->doQuery(
626 "SELECT NAME AS idColumn FROM SYS.IDENTITY_COLUMNS " .
627 "WHERE OBJECT_NAME(OBJECT_ID)='{$tableRaw}'"
629 if ( $res && sqlsrv_has_rows( $res ) ) {
630 // There is an identity for this table.
631 $identityArr = sqlsrv_fetch_array( $res, SQLSRV_FETCH_ASSOC
);
632 $identity = array_pop( $identityArr );
634 sqlsrv_free_stmt( $res );
636 // Determine binary/varbinary fields so we can encode data as a hex string like 0xABCDEF
637 $binaryColumns = $this->getBinaryColumns( $table );
639 // INSERT IGNORE is not supported by SQL Server
640 // remove IGNORE from options list and set ignore flag to true
641 if ( in_array( 'IGNORE', $options ) ) {
642 $options = array_diff( $options, [ 'IGNORE' ] );
643 $this->ignoreDupKeyErrors
= true;
647 foreach ( $arrToInsert as $a ) {
648 // start out with empty identity column, this is so we can return
649 // it as a result of the INSERT logic
652 $identityClause = '';
654 // if we have an identity column
657 foreach ( $a as $k => $v ) {
658 if ( $k == $identity ) {
659 if ( !is_null( $v ) ) {
660 // there is a value being passed to us,
661 // we need to turn on and off inserted identity
662 $sqlPre = "SET IDENTITY_INSERT $table ON;";
663 $sqlPost = ";SET IDENTITY_INSERT $table OFF;";
665 // we can't insert NULL into an identity column,
666 // so remove the column from the insert.
672 // we want to output an identity column as result
673 $identityClause = "OUTPUT INSERTED.$identity ";
676 $keys = array_keys( $a );
678 // Build the actual query
679 $sql = $sqlPre . 'INSERT ' . implode( ' ', $options ) .
680 " INTO $table (" . implode( ',', $keys ) . ") $identityClause VALUES (";
683 foreach ( $a as $key => $value ) {
684 if ( isset( $binaryColumns[$key] ) ) {
685 $value = new MssqlBlob( $value );
692 if ( is_null( $value ) ) {
695 $sql .= $this->addQuotes( $value );
698 $sql .= ')' . $sqlPost;
701 $this->scrollableCursor
= false;
703 $ret = $this->query( $sql );
704 } catch ( Exception
$e ) {
705 $this->scrollableCursor
= true;
706 $this->ignoreDupKeyErrors
= false;
709 $this->scrollableCursor
= true;
711 if ( $ret instanceof IResultWrapper
&& !is_null( $identity ) ) {
712 // Then we want to get the identity column value we were assigned and save it off
713 $row = $ret->fetchObject();
714 if ( is_object( $row ) ) {
715 $this->lastInsertId
= $row->$identity;
716 // It seems that mAffectedRows is -1 sometimes when OUTPUT INSERTED.identity is
717 // used if we got an identity back, we know for sure a row was affected, so
719 if ( $this->lastAffectedRowCount
== -1 ) {
720 $this->lastAffectedRowCount
= 1;
726 $this->ignoreDupKeyErrors
= false;
732 * INSERT SELECT wrapper
733 * $varMap must be an associative array of the form [ 'dest1' => 'source1', ... ]
734 * Source items may be literals rather than field names, but strings should
735 * be quoted with Database::addQuotes().
736 * @param string $destTable
737 * @param array|string $srcTable May be an array of tables.
738 * @param array $varMap
739 * @param array $conds May be "*" to copy the whole table.
740 * @param string $fname
741 * @param array $insertOptions
742 * @param array $selectOptions
743 * @param array $selectJoinConds
746 protected function nativeInsertSelect( $destTable, $srcTable, $varMap, $conds, $fname = __METHOD__
,
747 $insertOptions = [], $selectOptions = [], $selectJoinConds = []
749 $this->scrollableCursor
= false;
751 parent
::nativeInsertSelect(
761 } catch ( Exception
$e ) {
762 $this->scrollableCursor
= true;
765 $this->scrollableCursor
= true;
769 * UPDATE wrapper. Takes a condition array and a SET array.
771 * @param string $table Name of the table to UPDATE. This will be passed through
772 * Database::tableName().
774 * @param array $values An array of values to SET. For each array element,
775 * the key gives the field name, and the value gives the data
776 * to set that field to. The data will be quoted by
777 * Database::addQuotes().
779 * @param array $conds An array of conditions (WHERE). See
780 * Database::select() for the details of the format of
781 * condition arrays. Use '*' to update all rows.
783 * @param string $fname The function name of the caller (from __METHOD__),
784 * for logging and profiling.
786 * @param array $options An array of UPDATE options, can be:
787 * - IGNORE: Ignore unique key conflicts
788 * - LOW_PRIORITY: MySQL-specific, see MySQL manual.
790 * @throws DBUnexpectedError
793 function update( $table, $values, $conds, $fname = __METHOD__
, $options = [] ) {
794 $table = $this->tableName( $table );
795 $binaryColumns = $this->getBinaryColumns( $table );
797 $opts = $this->makeUpdateOptions( $options );
798 $sql = "UPDATE $opts $table SET " . $this->makeList( $values, LIST_SET
, $binaryColumns );
800 if ( $conds !== [] && $conds !== '*' ) {
801 $sql .= " WHERE " . $this->makeList( $conds, LIST_AND
, $binaryColumns );
804 $this->scrollableCursor
= false;
806 $this->query( $sql );
807 } catch ( Exception
$e ) {
808 $this->scrollableCursor
= true;
811 $this->scrollableCursor
= true;
816 * Makes an encoded list of strings from an array
817 * @param array $a Containing the data
818 * @param int $mode Constant
819 * - LIST_COMMA: comma separated, no field names
820 * - LIST_AND: ANDed WHERE clause (without the WHERE). See
821 * the documentation for $conds in Database::select().
822 * - LIST_OR: ORed WHERE clause (without the WHERE)
823 * - LIST_SET: comma separated with field names, like a SET clause
824 * - LIST_NAMES: comma separated field names
825 * @param array $binaryColumns Contains a list of column names that are binary types
826 * This is a custom parameter only present for MS SQL.
828 * @throws DBUnexpectedError
831 public function makeList( $a, $mode = LIST_COMMA
, $binaryColumns = [] ) {
832 if ( !is_array( $a ) ) {
833 throw new DBUnexpectedError( $this, __METHOD__
. ' called with incorrect parameters' );
836 if ( $mode != LIST_NAMES
) {
837 // In MS SQL, values need to be specially encoded when they are
838 // inserted into binary fields. Perform this necessary encoding
839 // for the specified set of columns.
840 foreach ( array_keys( $a ) as $field ) {
841 if ( !isset( $binaryColumns[$field] ) ) {
845 if ( is_array( $a[$field] ) ) {
846 foreach ( $a[$field] as &$v ) {
847 $v = new MssqlBlob( $v );
851 $a[$field] = new MssqlBlob( $a[$field] );
856 return parent
::makeList( $a, $mode );
860 * @param string $table
861 * @param string $field
862 * @return int Returns the size of a text field, or -1 for "unlimited"
864 public function textFieldSize( $table, $field ) {
865 $table = $this->tableName( $table );
866 $sql = "SELECT CHARACTER_MAXIMUM_LENGTH,DATA_TYPE FROM INFORMATION_SCHEMA.Columns
867 WHERE TABLE_NAME = '$table' AND COLUMN_NAME = '$field'";
868 $res = $this->query( $sql );
869 $row = $this->fetchRow( $res );
871 if ( strtolower( $row['DATA_TYPE'] ) != 'text' ) {
872 $size = $row['CHARACTER_MAXIMUM_LENGTH'];
879 * Construct a LIMIT query with optional offset
880 * This is used for query pages
882 * @param string $sql SQL query we will append the limit too
883 * @param int $limit The SQL limit
884 * @param bool|int $offset The SQL offset (default false)
885 * @return array|string
886 * @throws DBUnexpectedError
888 public function limitResult( $sql, $limit, $offset = false ) {
889 if ( $offset === false ||
$offset == 0 ) {
890 if ( strpos( $sql, "SELECT" ) === false ) {
891 return "TOP {$limit} " . $sql;
893 return preg_replace( '/\bSELECT(\s+DISTINCT)?\b/Dsi',
894 'SELECT$1 TOP ' . $limit, $sql, 1 );
897 // This one is fun, we need to pull out the select list as well as any ORDER BY clause
898 $select = $orderby = [];
899 $s1 = preg_match( '#SELECT\s+(.+?)\s+FROM#Dis', $sql, $select );
900 $s2 = preg_match( '#(ORDER BY\s+.+?)(\s*FOR XML .*)?$#Dis', $sql, $orderby );
902 $first = $offset +
1;
903 $last = $offset +
$limit;
904 $sub1 = 'sub_' . $this->subqueryId
;
905 $sub2 = 'sub_' . ( $this->subqueryId +
1 );
906 $this->subqueryId +
= 2;
909 throw new DBUnexpectedError( $this, "Attempting to LIMIT a non-SELECT query\n" );
913 $overOrder = 'ORDER BY (SELECT 1)';
915 if ( !isset( $orderby[2] ) ||
!$orderby[2] ) {
916 // don't need to strip it out if we're using a FOR XML clause
917 $sql = str_replace( $orderby[1], '', $sql );
919 $overOrder = $orderby[1];
920 $postOrder = ' ' . $overOrder;
922 $sql = "SELECT {$select[1]}
924 SELECT ROW_NUMBER() OVER({$overOrder}) AS rowNumber, *
925 FROM ({$sql}) {$sub1}
927 WHERE rowNumber BETWEEN {$first} AND {$last}{$postOrder}";
934 * If there is a limit clause, parse it, strip it, and pass the remaining
935 * SQL through limitResult() with the appropriate parameters. Not the
936 * prettiest solution, but better than building a whole new parser. This
937 * exists becase there are still too many extensions that don't use dynamic
941 * @return array|mixed|string
943 public function LimitToTopN( $sql ) {
944 // Matches: LIMIT {[offset,] row_count | row_count OFFSET offset}
945 $pattern = '/\bLIMIT\s+((([0-9]+)\s*,\s*)?([0-9]+)(\s+OFFSET\s+([0-9]+))?)/i';
946 if ( preg_match( $pattern, $sql, $matches ) ) {
947 $row_count = $matches[4];
948 $offset = $matches[3] ?
: $matches[6] ?
: false;
950 // strip the matching LIMIT clause out
951 $sql = str_replace( $matches[0], '', $sql );
953 return $this->limitResult( $sql, $row_count, $offset );
960 * @return string Wikitext of a link to the server software's web site
962 public function getSoftwareLink() {
963 return "[{{int:version-db-mssql-url}} MS SQL Server]";
967 * @return string Version information from the database
969 public function getServerVersion() {
970 $server_info = sqlsrv_server_info( $this->conn
);
971 $version = $server_info['SQLServerVersion'] ??
'Error';
977 * @param string $table
978 * @param string $fname
981 public function tableExists( $table, $fname = __METHOD__
) {
982 list( $db, $schema, $table ) = $this->tableName( $table, 'split' );
984 if ( $db !== false ) {
986 $this->queryLogger
->error( "Attempting to call tableExists on a remote table" );
990 if ( $schema === false ) {
991 $schema = $this->dbSchema();
994 $res = $this->query( "SELECT 1 FROM INFORMATION_SCHEMA.TABLES
995 WHERE TABLE_TYPE = 'BASE TABLE'
996 AND TABLE_SCHEMA = '$schema' AND TABLE_NAME = '$table'" );
998 if ( $res->numRows() ) {
1006 * Query whether a given column exists in the mediawiki schema
1007 * @param string $table
1008 * @param string $field
1009 * @param string $fname
1012 public function fieldExists( $table, $field, $fname = __METHOD__
) {
1013 list( $db, $schema, $table ) = $this->tableName( $table, 'split' );
1015 if ( $db !== false ) {
1017 $this->queryLogger
->error( "Attempting to call fieldExists on a remote table" );
1021 $res = $this->query( "SELECT 1 FROM INFORMATION_SCHEMA.COLUMNS
1022 WHERE TABLE_SCHEMA = '$schema' AND TABLE_NAME = '$table' AND COLUMN_NAME = '$field'" );
1024 if ( $res->numRows() ) {
1031 public function fieldInfo( $table, $field ) {
1032 list( $db, $schema, $table ) = $this->tableName( $table, 'split' );
1034 if ( $db !== false ) {
1036 $this->queryLogger
->error( "Attempting to call fieldInfo on a remote table" );
1040 $res = $this->query( "SELECT * FROM INFORMATION_SCHEMA.COLUMNS
1041 WHERE TABLE_SCHEMA = '$schema' AND TABLE_NAME = '$table' AND COLUMN_NAME = '$field'" );
1043 $meta = $res->fetchRow();
1045 return new MssqlField( $meta );
1051 protected function doSavepoint( $identifier, $fname ) {
1052 $this->query( 'SAVE TRANSACTION ' . $this->addIdentifierQuotes( $identifier ), $fname );
1055 protected function doReleaseSavepoint( $identifier, $fname ) {
1056 // Not supported. Also not really needed, a new doSavepoint() for the
1057 // same identifier will overwrite the old.
1060 protected function doRollbackToSavepoint( $identifier, $fname ) {
1061 $this->query( 'ROLLBACK TRANSACTION ' . $this->addIdentifierQuotes( $identifier ), $fname );
1064 protected function doBegin( $fname = __METHOD__
) {
1065 if ( !sqlsrv_begin_transaction( $this->conn
) ) {
1066 $this->reportQueryError( $this->lastError(), $this->lastErrno(), 'BEGIN', $fname );
1072 * @param string $fname
1074 protected function doCommit( $fname = __METHOD__
) {
1075 if ( !sqlsrv_commit( $this->conn
) ) {
1076 $this->reportQueryError( $this->lastError(), $this->lastErrno(), 'COMMIT', $fname );
1081 * Rollback a transaction.
1082 * No-op on non-transactional databases.
1083 * @param string $fname
1085 protected function doRollback( $fname = __METHOD__
) {
1086 if ( !sqlsrv_rollback( $this->conn
) ) {
1087 $this->queryLogger
->error(
1088 "{fname}\t{db_server}\t{errno}\t{error}\t",
1089 $this->getLogContext( [
1090 'errno' => $this->lastErrno(),
1091 'error' => $this->lastError(),
1093 'trace' => ( new RuntimeException() )->getTraceAsString()
1103 public function strencode( $s ) {
1104 // Should not be called by us
1105 return str_replace( "'", "''", $s );
1109 * @param string|int|null|bool|Blob $s
1110 * @return string|int
1112 public function addQuotes( $s ) {
1113 if ( $s instanceof MssqlBlob
) {
1115 } elseif ( $s instanceof Blob
) {
1116 // this shouldn't really ever be called, but it's here if needed
1117 // (and will quite possibly make the SQL error out)
1118 $blob = new MssqlBlob( $s->fetch() );
1119 return $blob->fetch();
1121 if ( is_bool( $s ) ) {
1124 return parent
::addQuotes( $s );
1132 public function addIdentifierQuotes( $s ) {
1133 // http://msdn.microsoft.com/en-us/library/aa223962.aspx
1134 return '[' . $s . ']';
1138 * @param string $name
1141 public function isQuotedIdentifier( $name ) {
1142 return strlen( $name ) && $name[0] == '[' && substr( $name, -1, 1 ) == ']';
1146 * MS SQL supports more pattern operators than other databases (ex: [,],^)
1149 * @param string $escapeChar
1152 protected function escapeLikeInternal( $s, $escapeChar = '`' ) {
1153 return str_replace( [ $escapeChar, '%', '_', '[', ']', '^' ],
1154 [ "{$escapeChar}{$escapeChar}", "{$escapeChar}%", "{$escapeChar}_",
1155 "{$escapeChar}[", "{$escapeChar}]", "{$escapeChar}^" ],
1159 protected function doSelectDomain( DatabaseDomain
$domain ) {
1160 if ( $domain->getSchema() !== null ) {
1161 throw new DBExpectedError(
1163 __CLASS__
. ": domain '{$domain->getId()}' has a schema component"
1167 $database = $domain->getDatabase();
1168 if ( $database !== $this->getDBname() ) {
1169 $sql = 'USE ' . $this->addIdentifierQuotes( $database );
1170 list( $res, $err, $errno ) =
1171 $this->executeQuery( $sql, __METHOD__
, self
::QUERY_IGNORE_DBO_TRX
);
1173 if ( $res === false ) {
1174 $this->reportQueryError( $err, $errno, $sql, __METHOD__
);
1175 return false; // unreachable
1178 // Update that domain fields on success (no exception thrown)
1179 $this->currentDomain
= $domain;
1185 * @param array $options An associative array of options to be turned into
1186 * an SQL query, valid keys are listed in the function.
1189 public function makeSelectOptions( $options ) {
1194 foreach ( $options as $key => $option ) {
1195 if ( is_numeric( $key ) ) {
1196 $noKeyOptions[$option] = true;
1200 $tailOpts .= $this->makeGroupByWithHaving( $options );
1202 $tailOpts .= $this->makeOrderBy( $options );
1204 if ( isset( $noKeyOptions['DISTINCT'] ) ||
isset( $noKeyOptions['DISTINCTROW'] ) ) {
1205 $startOpts .= 'DISTINCT';
1208 if ( isset( $noKeyOptions['FOR XML'] ) ) {
1209 // used in group concat field emulation
1210 $tailOpts .= " FOR XML PATH('')";
1213 // we want this to be compatible with the output of parent::makeSelectOptions()
1214 return [ $startOpts, '', $tailOpts, '', '' ];
1217 public function getType() {
1222 * @param array $stringList
1225 public function buildConcat( $stringList ) {
1226 return implode( ' + ', $stringList );
1230 * Build a GROUP_CONCAT or equivalent statement for a query.
1231 * MS SQL doesn't have GROUP_CONCAT so we emulate it with other stuff (and boy is it nasty)
1233 * This is useful for combining a field for several rows into a single string.
1234 * NULL values will not appear in the output, duplicated values will appear,
1235 * and the resulting delimiter-separated values have no defined sort order.
1236 * Code using the results may need to use the PHP unique() or sort() methods.
1238 * @param string $delim Glue to bind the results together
1239 * @param string|array $table Table name
1240 * @param string $field Field name
1241 * @param string|array $conds Conditions
1242 * @param string|array $join_conds Join conditions
1243 * @return string SQL text
1246 public function buildGroupConcatField( $delim, $table, $field, $conds = '',
1249 $gcsq = 'gcsq_' . $this->subqueryId
;
1250 $this->subqueryId++
;
1252 $delimLen = strlen( $delim );
1253 $fld = "{$field} + {$this->addQuotes( $delim )}";
1254 $sql = "(SELECT LEFT({$field}, LEN({$field}) - {$delimLen}) FROM ("
1255 . $this->selectSQLText( $table, $fld, $conds, null, [ 'FOR XML' ], $join_conds )
1256 . ") {$gcsq} ({$field}))";
1261 public function buildSubstring( $input, $startPosition, $length = null ) {
1262 $this->assertBuildSubstringParams( $startPosition, $length );
1263 if ( $length === null ) {
1265 * MSSQL doesn't allow an empty length parameter, so when we don't want to limit the
1266 * length returned use the default maximum size of text.
1267 * @see https://docs.microsoft.com/en-us/sql/t-sql/statements/set-textsize-transact-sql
1269 $length = 2147483647;
1271 return 'SUBSTRING(' . implode( ',', [ $input, $startPosition, $length ] ) . ')';
1275 * Returns an associative array for fields that are of type varbinary, binary, or image
1276 * $table can be either a raw table name or passed through tableName() first
1277 * @param string $table
1280 private function getBinaryColumns( $table ) {
1281 $tableRawArr = explode( '.', preg_replace( '#\[([^\]]*)\]#', '$1', $table ) );
1282 $tableRaw = array_pop( $tableRawArr );
1284 if ( $this->binaryColumnCache
=== null ) {
1285 $this->populateColumnCaches();
1288 return $this->binaryColumnCache
[$tableRaw] ??
[];
1292 * @param string $table
1295 private function getBitColumns( $table ) {
1296 $tableRawArr = explode( '.', preg_replace( '#\[([^\]]*)\]#', '$1', $table ) );
1297 $tableRaw = array_pop( $tableRawArr );
1299 if ( $this->bitColumnCache
=== null ) {
1300 $this->populateColumnCaches();
1303 return $this->bitColumnCache
[$tableRaw] ??
[];
1306 private function populateColumnCaches() {
1307 $res = $this->select( 'INFORMATION_SCHEMA.COLUMNS', '*',
1309 'TABLE_CATALOG' => $this->getDBname(),
1310 'TABLE_SCHEMA' => $this->dbSchema(),
1311 'DATA_TYPE' => [ 'varbinary', 'binary', 'image', 'bit' ]
1314 $this->binaryColumnCache
= [];
1315 $this->bitColumnCache
= [];
1316 foreach ( $res as $row ) {
1317 if ( $row->DATA_TYPE
== 'bit' ) {
1318 $this->bitColumnCache
[$row->TABLE_NAME
][$row->COLUMN_NAME
] = $row;
1320 $this->binaryColumnCache
[$row->TABLE_NAME
][$row->COLUMN_NAME
] = $row;
1326 * @param string $name
1327 * @param string $format One of "quoted" (default), "raw", or "split".
1328 * @return string|array When the requested $format is "split", a list of database, schema, and
1329 * table name is returned. Database and schema can be `false`.
1331 function tableName( $name, $format = 'quoted' ) {
1332 # Replace reserved words with better ones
1335 return $this->realTableName( 'mwuser', $format );
1337 return $this->realTableName( $name, $format );
1342 * call this instead of tableName() in the updater when renaming tables
1343 * @param string $name
1344 * @param string $format One of "quoted" (default), "raw", or "split".
1345 * @return string|array When the requested $format is "split", a list of database, schema, and
1346 * table name is returned. Database and schema can be `false`.
1349 function realTableName( $name, $format = 'quoted' ) {
1350 $table = parent
::tableName( $name, $format );
1351 if ( $format == 'split' ) {
1352 // Used internally, we want the schema split off from the table name and returned
1353 // as a list with 3 elements (database, schema, table)
1354 return array_pad( explode( '.', $table, 3 ), -3, false );
1361 * @param string $tableName
1362 * @param string $fName
1363 * @return bool|IResultWrapper
1366 public function dropTable( $tableName, $fName = __METHOD__
) {
1367 if ( !$this->tableExists( $tableName, $fName ) ) {
1371 // parent function incorrectly appends CASCADE, which we don't want
1372 $sql = "DROP TABLE " . $this->tableName( $tableName );
1374 return $this->query( $sql, $fName );
1378 * Called in the installer and updater.
1379 * Probably doesn't need to be called anywhere else in the codebase.
1380 * @param bool|null $value
1383 public function prepareStatements( $value = null ) {
1384 $old = $this->prepareStatements
;
1385 if ( $value !== null ) {
1386 $this->prepareStatements
= $value;
1393 * Called in the installer and updater.
1394 * Probably doesn't need to be called anywhere else in the codebase.
1395 * @param bool|null $value
1398 public function scrollableCursor( $value = null ) {
1399 $old = $this->scrollableCursor
;
1400 if ( $value !== null ) {
1401 $this->scrollableCursor
= $value;
1407 public function buildStringCast( $field ) {
1408 return "CAST( $field AS NVARCHAR )";
1411 public static function getAttributes() {
1412 return [ self
::ATTR_SCHEMAS_AS_TABLE_GROUPS
=> true ];
1417 * @deprecated since 1.29
1419 class_alias( DatabaseMssql
::class, 'DatabaseMssql' );